package cn.net.susan.util;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 苏三，该项目是知识星球：java突击队 的内部项目
 * @date 2024/2/12 下午9:00
 */
public abstract class IpUtil {

    private static final String LOCAL_IP = "127.0.0.1";

    private IpUtil() {
    }

    /**
     * 获取用户IP
     *
     * @param request 请求
     * @return 用户IP
     */
    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            return LOCAL_IP;
        }
        return ip;
    }
}
